/**
 * @file main.c
 * @brief 温湿度采集后端服务程序入口
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include "mqtt_client.h"
#include "modbus.h"
#include "daemon.h"

// 全局变量，用于控制程序运行
static volatile int g_running = 1;

/**
 * @brief 信号处理函数
 */
static void signal_handler(int signo) {
    if (signo == SIGINT || signo == SIGTERM) {
        g_running = 0;
    }
}

/**
 * @brief 打印帮助信息
 */
static void print_usage(const char *prog_name) {
    printf("Usage: %s [options]\n", prog_name);
    printf("Options:\n");
    printf("  -d, --daemon        Run as daemon\n");
    printf("  -h, --help         Show this help message\n");
    printf("  -p, --port PORT    Serial port device (default: /dev/ttyS1)\n");
    printf("  -b, --broker HOST  MQTT broker address (default: localhost)\n");
    printf("  -t, --topic TOPIC  MQTT topic (default: sensors/th)\n");
}

int main(int argc, char *argv[]) {
    int daemon_mode = 0;
    char serial_port[64] = "/dev/ttyO1";
    char broker_address[128] = "localhost";
    char mqtt_topic[128] = "sensors/th";
    
    // 命令行选项
    static struct option long_options[] = {
        {"daemon", no_argument, 0, 'd'},
        {"help", no_argument, 0, 'h'},
        {"port", required_argument, 0, 'p'},
        {"broker", required_argument, 0, 'b'},
        {"topic", required_argument, 0, 't'},
        {0, 0, 0, 0}
    };

    // 解析命令行参数
    int opt;
    while ((opt = getopt_long(argc, argv, "dhp:b:t:", long_options, NULL)) != -1) {
        switch (opt) {
            case 'd':
                daemon_mode = 1;
                break;
            case 'h':
                print_usage(argv[0]);
                return 0;
            case 'p':
                strncpy(serial_port, optarg, sizeof(serial_port) - 1);
                break;
            case 'b':
                strncpy(broker_address, optarg, sizeof(broker_address) - 1);
                break;
            case 't':
                strncpy(mqtt_topic, optarg, sizeof(mqtt_topic) - 1);
                break;
            default:
                print_usage(argv[0]);
                return 1;
        }
    }

    // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    // 守护进程模式
    if (daemon_mode) {
        if (daemon_init() < 0) {
            fprintf(stderr, "Failed to initialize daemon\n");
            return 1;
        }
    }

    // 初始化Modbus
    if (modbus_init(serial_port) < 0) {
        fprintf(stderr, "Failed to initialize modbus\n");
        return 1;
    }

    // 初始化MQTT客户端
    if (mqtt_client_init(broker_address, mqtt_topic) < 0) {
        fprintf(stderr, "Failed to initialize MQTT client\n");
        modbus_cleanup();
        return 1;
    }

    // 主循环
    while (g_running) {
        // 读取温湿度数据
        float temperature, humidity;
        if (modbus_read_th(&temperature, &humidity) == 0) {
            // 发布数据到MQTT服务器
            mqtt_client_publish(temperature, humidity);
        }
        
        // 等待一段时间再次采集
        sleep(1);
    }

    // 清理资源
    mqtt_client_cleanup();
    modbus_cleanup();

    return 0;
}